{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "55983c66",
   "metadata": {},
   "source": [
    "# Getting started with Amazon Braket\n",
    "In this hello-world tutorial we prepare a maximally entangled Bell state between two qubits. We then run our circuit on a local simulator and obtain the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ea438f2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# general imports\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "import string\n",
    "import time\n",
    "import numpy as np\n",
    "\n",
    "# AWS imports: Import Braket SDK modules\n",
    "from braket.circuits import Circuit, Gate, Instruction, circuit, Observable\n",
    "from braket.devices import LocalSimulator\n",
    "from braket.aws import AwsDevice, AwsQuantumTask"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8bede24",
   "metadata": {},
   "source": [
    "## Build a circuit\n",
    "Let's build a Bell state with two qubits. By calling Circuit() we create an empty circuit, and we can just add gates to the circuit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "48169f08",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T  : |0|1|\n",
      "          \n",
      "q0 : -H-C-\n",
      "        | \n",
      "q1 : ---X-\n",
      "\n",
      "T  : |0|1|\n"
     ]
    }
   ],
   "source": [
    "# build a Bell state with two qubits. Here 'cnot(control=0, target=1)' can be simplified as 'cnot(0,1)'\n",
    "bell = Circuit().h(0).cnot(control=0, target=1)\n",
    "\n",
    "print(bell)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf2f1451",
   "metadata": {},
   "source": [
    "## Submit the circuit to the local simulator and obtain the results\n",
    "Here we submit our circuit to the local simulator and obtain the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8f3fa0c5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({'00': 500, '11': 500})\n"
     ]
    }
   ],
   "source": [
    "# set up device\n",
    "device = LocalSimulator()\n",
    "\n",
    "# run circuit\n",
    "result = device.run(bell, shots=1000).result()\n",
    "# get measurement shots\n",
    "counts = result.measurement_counts\n",
    "# print counts\n",
    "print(counts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "470248bc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYUAAAEGCAYAAACKB4k+AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAQiklEQVR4nO3df6xfd13H8edrHQwYW1zZ3SztZhfSGDtgQ64DRAwwwiooXdBhp2gDizVxKosmpsNE8EfjSFCZyIwVGOXnUkFcHRFoKnNBHV0HZawbcw2bW21tu01kExy0vP3jnn72bXvv3dd1537v+n0+kptzzud8zrnv23zTV875nO/npKqQJAnghFEXIEmaPwwFSVJjKEiSGkNBktQYCpKk5sRRF3AsTj/99Fq6dOmoy5Ckp5Rbb731gaqamG7fUzoUli5dyrZt20ZdhiQ9pST595n2eftIktQYCpKkxlCQJDWGgiSpMRQkSY2hIElqeg2FJPcm+VqS7Um2dW0Lk2xOcne3PG2g/5VJdia5K8lFfdYmSTraXFwpvKqqzq+qyW57LbClqpYBW7ptkiwHVgHnAiuAa5IsmIP6JEmdUdw+Wgls6NY3ABcPtF9XVY9W1T3ATuCCEdQnSWOr7280F/D5JAX8VVWtB86sqj0AVbUnyRld38XAzQPH7uraDpNkDbAG4Oyzzz6m4pau/cwxHa/j171XvX7UJQB+RjWzvj6jfYfCy6tqd/cf/+YkX5+lb6ZpO+q1cF2wrAeYnJz0tXGS9CTq9fZRVe3ulvuATzN1O2hvkkUA3XJf130XcNbA4UuA3X3WJ0k6XG+hkOTkJKccWgdeC9wObAJWd91WA9d365uAVUlOSnIOsAzY2ld9kqSj9Xn76Ezg00kO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OTvKZJF9NcnuSn0/ym8BzgS8k+QJMBUmSP0jyJeBlh843sG9dd46bk5zZtT+v276lO/aRrn1Rkpu6Gm5P8orR/DNpHBgKEvwwsL6qXgh8C/i1Qzuqai3wnao6v6p+kak5/ndX1Xnd1cVnq+rPmZo/6lVV9aru0JOB26vqJVX1xSN+38nAzVV1HlPvBviVrv1q4Oqq+rHufIf8AvC5qjofOA/Y/uT96dLhDAUJ7q+qf+7WPwr8xCx9vwa8Jsm7kryiqv57hn4HgU/NsO+7wA3d+q3A0m79ZcDfdOsfH+h/C/CWJO8EXlBVD89Sn3RMDAXp6KnDZxxoq6p/A17MVDj8cZLfm6Hr/84yjvC9emww7yBw4qzFTb1w5ieB/wA+kuSXZ+svHQtDQYKzk7ysW78UOPJ2z/eSPA0gyXOBb1fVR4F3Az/a9XkYOOUY67gZ+NlufdWhxiQ/BOyrqr8GPjDwO6UnnaEgwZ3A6iS3AQuBvzxi/3rgtiQfA14AbE2yHfhd4I8G+vzDoYHmJ+gK4LeSbAUWAYduTb0S2J7kK0yFxtXH8DukWflIqjRPdN9z+E5VVZJVwKVVtXLUdWm8zHovU9KcejHwF0nC1PsC3jriejSGvFKQJDWOKUiSGkNBktQYCpKkxlCQJDWGgiSp+T9RtToxqncXawAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# plot the results\n",
    "plt.bar(counts.keys(), counts.values());\n",
    "plt.xlabel('bitstrings');\n",
    "plt.ylabel('counts');"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4154b2c",
   "metadata": {},
   "source": [
    "## Running the circuit on a managed simulator\n",
    "Next, we run our circuit on a managed simulator.\n",
    "In addition to the local simulator, Amazon Braket offers three managed simulators: a full state-vector simulator SV1,  a tensor-network simulator TN1, and a density-matrix simulator DM1. As shown below, one can seamlessly swap between different devices without any modifications to the circuit definition, by just re-defining the device object.\n",
    "\n",
    "Running on a managed simulator adds some latency overhead, but is beneficial for larger circuits by leveraging the optimized cloud hardware infrastructure. Moreover, all your results will be stored reliably in S3. Here, as part of the API call with run() you need to supply a S3 location where the metadata and results associated with this circuit execution will be stored."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f395667",
   "metadata": {},
   "source": [
    "**NOTE:** Enter your desired device and S3 location (bucket and key) below. If you are working with the local simulator LocalSimulator() you do not need to specify any S3 location. However, if you are using a managed device or any QPU devices you need to specify the S3 location where your results will be stored. Remember that bucket names for Amazon Braket always begin with \"amazon-braket-\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c50dc866",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enter the S3 bucket you created during onboarding in the code below\n",
    "my_bucket = # TODO Fill in the name of the bucket\n",
    "my_prefix = \"braket-training\" # the name of the folder in the bucket\n",
    "s3_folder = (my_bucket, my_prefix)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "106aa0a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({'11': 535, '00': 465})\n",
      "Counts for all-zero bitstring: 465\n",
      "Counts for all-one bitstring: 535\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYUAAAEGCAYAAACKB4k+AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAQkklEQVR4nO3df6xfdX3H8eeLoqiIGR2lKxQtMc0yUGHzijrnomKk080SN1xxzkbJWDK2SbZkKS6Z7kczTNwmc7Kk81f9STodo8NMJZ2MuE1L0YotyGiEQdeuLTCHTIe2vvfH9/TDt+29t19azv1e7n0+kuac8z6fc77vL7nhlXPO95yTqkKSJIATxt2AJGn2MBQkSY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4KmpVwBbk3yNQWhccxyfIU3Ln6RKs0R3n8P3qqqSrAIuraqV4+5L88u05zIlzagXAn+VJAzeafG2MfejecgjBUlS4zUFSVJjKEiSGkNBktQYCpKkxlCQJDX/D80sM/OWoHGIAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# set up the managed simulator SV1\n",
    "device = AwsDevice(\"arn:aws:braket:::device/quantum-simulator/amazon/sv1\")\n",
    "\n",
    "bell = Circuit().h(0).cnot(control=0, target=1)\n",
    "\n",
    "# run circuit on SV1\n",
    "result = device.run(bell, s3_folder, shots=1000).result()\n",
    "counts = result.measurement_counts\n",
    "print(counts)\n",
    "\n",
    "# plot using Counter\n",
    "plt.bar(counts.keys(), counts.values());\n",
    "plt.xlabel('bitstrings');\n",
    "plt.ylabel('counts');  \n",
    "\n",
    "# print counts of all-zero-string\n",
    "print('Counts for all-zero bitstring:', counts['00'])\n",
    "# print counts of all-one-string\n",
    "print('Counts for all-one bitstring:', counts['11'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98d73555",
   "metadata": {},
   "source": [
    "Now let's try the TN1 simulator:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "41ffe96a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({'00': 519, '11': 481})\n",
      "Counts for all-zero bitstring: 519\n",
      "Counts for all-one bitstring: 481\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYUAAAEGCAYAAACKB4k+AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAQi0lEQVR4nO3df6xfdX3H8ee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/mbcfOHHW4gYfnPkp4D+Ajyb5ldn6S8fCUJDgOUle1q1fBhx6uef7SZ4CkORM4DtV9THg3cCPdX0eAU45xjq+DPxct77yQGOS5wJ7quqvgQ8M/UzpCWcoSHAHsCrJrcBC4K8O2b8OuDXJx4EXAFuSbAN+D/jjoT7/cOBG81G6EvjtJFuARcCBS1OvBLYl+RqD0LjmGH6GNCsfSZXmie49h+9WVSVZCVxWVSvGXZcmy6zXMiXNqRcDf5kkDL4X8NYx16MJ5EhBktR4T0GS1BgKkqTGUJAkNYaCJKkxFCRJzf8BHz49XThuKakAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# set up the managed simulator TN1\n",
    "device = AwsDevice(\"arn:aws:braket:::device/quantum-simulator/amazon/tn1\")\n",
    "\n",
    "bell = Circuit().h(0).cnot(control=0, target=1)\n",
    "\n",
    "# run circuit on SV1\n",
    "result = device.run(bell, s3_folder, shots=1000).result()\n",
    "counts = result.measurement_counts\n",
    "print(counts)\n",
    "\n",
    "# plot using Counter\n",
    "plt.bar(counts.keys(), counts.values());\n",
    "plt.xlabel('bitstrings');\n",
    "plt.ylabel('counts');  \n",
    "\n",
    "# print counts of all-zero-string\n",
    "print('Counts for all-zero bitstring:', counts['00'])\n",
    "# print counts of all-one-string\n",
    "print('Counts for all-one bitstring:', counts['11'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "853e5c89",
   "metadata": {},
   "source": [
    "## Running the circuit on a QPU\n",
    "Now let's run our circuit on QPU devices. We can run our circuit on both the superconducting machine from Rigetti and the ion-trap machine provided by IonQ. As shown below, one can seamlessly swap between different devices without any modifications to the circuit definition, by just re-defining the device object. We also show how to recover results using the unique ARN associated with every task. This tool is useful in order to deal with potential delays if your quantum task sits in the queue for some time waiting for execution."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9dc5b359",
   "metadata": {},
   "source": [
    "### Quantum Hardware: Rigetti\n",
    "Next we submit our circuit to the superconducting quantum chip provided by Rigetti. Depending on our position in the queue, we may have to wait for some time till our circuit is actually run. However, thanks to asynchronous execution, we can always come back and recover the results by providing the unique ID associated with every task."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6808d721",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status of task: CREATED\n"
     ]
    }
   ],
   "source": [
    "# set up device\n",
    "rigetti = AwsDevice(\"arn:aws:braket:::device/qpu/rigetti/Aspen-9\")\n",
    "\n",
    "# create a clean circuit with no result type attached.(This is because some result types are only supported when shots=0)\n",
    "bell = Circuit().h(0).cnot(0, 1)  \n",
    "\n",
    "# add the Z \\otimes Z expectation value\n",
    "bell.expectation(Observable.Z() @ Observable.Z(), target=[0,1])\n",
    "\n",
    "# run circuit \n",
    "rigetti_task = rigetti.run(bell, s3_folder, shots=1000)\n",
    "\n",
    "# get id and status of submitted task\n",
    "rigetti_task_id = rigetti_task.id\n",
    "rigetti_status = rigetti_task.state()\n",
    "# print('ID of task:', rigetti_task_id)\n",
    "print('Status of task:', rigetti_status)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40be9dee",
   "metadata": {},
   "source": [
    "The task is submitted and we can regularly (or irregularly) check the status of this task by executing the following cell. You may easily build logic around this query to wait for this task to complete before your code proceeds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9604a35e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status of (reconstructed) task: CREATED\n"
     ]
    }
   ],
   "source": [
    "# print status\n",
    "status = rigetti_task.state()\n",
    "print('Status of (reconstructed) task:', status)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d61faf40",
   "metadata": {},
   "source": [
    "### Quantum Hardware: IonQ\n",
    "Finally, we submit our example Bell state circuit to IonQ. To this end, we set the device as AwsDevice(\"arn:aws:braket:::device/qpu/ionq/ionQdevice\"). This task may not readily be executed but enter a queue for this specific machine. While we can interrupt our kernel (and work on something else), we can always recover our results using the unique ID of this task."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c47b57e8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status of task: CREATED\n"
     ]
    }
   ],
   "source": [
    "# set up device\n",
    "ionq = AwsDevice(\"arn:aws:braket:::device/qpu/ionq/ionQdevice\")\n",
    "\n",
    "# run circuit\n",
    "ionq_task = ionq.run(bell, s3_folder, shots=1000)\n",
    "\n",
    "# get id and status of submitted task\n",
    "ionq_task_id = ionq_task.id\n",
    "ionq_status = ionq_task.state()\n",
    "# print('ID of task:', ionq_task_id)\n",
    "print('Status of task:', ionq_status)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "2d4503a4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status of (reconstructed) task: CREATED\n"
     ]
    }
   ],
   "source": [
    "# print status\n",
    "status = ionq_task.state()\n",
    "print('Status of (reconstructed) task:', status)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6cbc3943",
   "metadata": {},
   "source": [
    "### Task Recovery\n",
    "By simply grabbing the unique task ID associated with the quantum tasks we have submitted above, we can recover this task at any point in time and (once the status is completed) visualize and analyze the corresponding results. Note that apart from other metadata, you can retrieve the compiled circuit that was actually run on the Rigetti device. More information about the compiling process can be found [here](https://pyquil-docs.rigetti.com/en/v2.22.0/compiler.html#partial). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "5c3f772b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status of (reconstructed) task: QUEUED\n",
      "\n",
      "\n",
      "Sorry, your task is still being processed and has not been finalized yet.\n"
     ]
    }
   ],
   "source": [
    "# recover task\n",
    "task_load = AwsQuantumTask(arn=rigetti_task_id)\n",
    "\n",
    "# print status\n",
    "status = task_load.state()\n",
    "print('Status of (reconstructed) task:', status)\n",
    "print('\\n')\n",
    "# wait for job to complete\n",
    "# terminal_states = ['COMPLETED', 'FAILED', 'CANCELLED']\n",
    "if status == 'COMPLETED':\n",
    "    # get results\n",
    "    rigetti_results = task_load.result()\n",
    "    # print(rigetti_results)\n",
    "    \n",
    "    # get all metadata of submitted task\n",
    "    metadata = task_load.metadata()\n",
    "    # example for metadata\n",
    "    shots = metadata['shots']\n",
    "    machine = metadata['deviceArn']\n",
    "    # print example metadata\n",
    "    print(\"{} shots taken on machine {}.\\n\".format(shots, machine))\n",
    "    \n",
    "    # get the compiled circuit\n",
    "    print(\"The compiled circuit is:\\n\", rigetti_results.additional_metadata.rigettiMetadata.compiledProgram)\n",
    "    \n",
    "    # get measurement counts\n",
    "    rigetti_counts = rigetti_results.measurement_counts\n",
    "    print('Measurement counts:', rigetti_counts)\n",
    "\n",
    "    # plot results: see effects of noise\n",
    "    plt.bar(rigetti_counts.keys(), rigetti_counts.values());\n",
    "    plt.xlabel('bitstrings');\n",
    "    plt.ylabel('counts');\n",
    "    plt.tight_layout();\n",
    "    plt.savefig('rigetti.png', dpi=700);\n",
    "    \n",
    "elif status in ['FAILED', 'CANCELLED']:\n",
    "    # print terminal message \n",
    "    print('Your task is in terminal status, but has not completed.')\n",
    "\n",
    "else:\n",
    "    # print current status\n",
    "    print('Sorry, your task is still being processed and has not been finalized yet.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "7789ea3d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status of (reconstructed) task: CREATED\n",
      "Sorry, your task is still being processed and has not been finalized yet.\n"
     ]
    }
   ],
   "source": [
    "# recover task\n",
    "task_load = AwsQuantumTask(arn=ionq_task_id)\n",
    "\n",
    "# print status\n",
    "status = task_load.state()\n",
    "print('Status of (reconstructed) task:', status)\n",
    "\n",
    "# wait for job to complete\n",
    "# terminal_states = ['COMPLETED', 'FAILED', 'CANCELLED']\n",
    "if status == 'COMPLETED':\n",
    "    # get results\n",
    "    results = task_load.result()\n",
    "    # print(rigetti_results)\n",
    "    \n",
    "    # get all metadata of submitted task\n",
    "    metadata = task_load.metadata()\n",
    "    # example for metadata\n",
    "    shots = metadata['shots']\n",
    "    machine = metadata['deviceArn']\n",
    "    # print example metadata\n",
    "    print(\"{} shots taken on machine {}.\".format(shots, machine))\n",
    "    \n",
    "    # get measurement counts\n",
    "    counts = results.measurement_counts\n",
    "    print('Measurement counts:', counts)\n",
    "\n",
    "    # plot results: see effects of noise\n",
    "    plt.bar(counts.keys(), counts.values());\n",
    "    plt.xlabel('bitstrings');\n",
    "    plt.ylabel('counts');\n",
    "    plt.tight_layout();\n",
    "    plt.savefig('bell_ionq.png', dpi=700);\n",
    "    \n",
    "elif status in ['FAILED', 'CANCELLED']:\n",
    "    # print terminal message \n",
    "    print('Your task is in terminal status, but has not completed.')\n",
    "\n",
    "else:\n",
    "    # print current status\n",
    "    print('Sorry, your task is still being processed and has not been finalized yet.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27f1defa",
   "metadata": {},
   "source": [
    "We have successfully recovered the results associated with the tasks that were queued up for the quantum hardware providers. Because of noise (decoherence) and other imperfections we cannot fully recover the exact results we have seen when using the classical simulator. To deal with that, in the fullness of time we will be able to use error correction techniques. As long as error correction is not available, it is important to benchmark our quantum results using classical simulators, whenever possible."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a19b8e14",
   "metadata": {},
   "source": [
    "### Supported gate sets by different devices\n",
    "\n",
    "First, let us check out the gate set currently supported by our SDK. Note that the QPU devices only support a subset of these gates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "53138e8b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gate set supported by SDK:\n",
      " ['CCNot', 'CNot', 'CPhaseShift', 'CPhaseShift00', 'CPhaseShift01', 'CPhaseShift10', 'CSwap', 'CY', 'CZ', 'H', 'I', 'ISwap', 'PSwap', 'PhaseShift', 'Rx', 'Ry', 'Rz', 'S', 'Si', 'Swap', 'T', 'Ti', 'Unitary', 'V', 'Vi', 'X', 'XX', 'XY', 'Y', 'YY', 'Z', 'ZZ']\n",
      "\n",
      "\n",
      "Gate set supported by the Rigetti device:\n",
      " ['cz', 'xy', 'ccnot', 'cnot', 'cphaseshift', 'cphaseshift00', 'cphaseshift01', 'cphaseshift10', 'cswap', 'h', 'i', 'iswap', 'phaseshift', 'pswap', 'rx', 'ry', 'rz', 's', 'si', 'swap', 't', 'ti', 'x', 'y', 'z']\n",
      "\n",
      "\n",
      "Gate set supported by the IonQ device:\n",
      " ['x', 'y', 'z', 'rx', 'ry', 'rz', 'h', 'cnot', 's', 'si', 't', 'ti', 'v', 'vi', 'xx', 'yy', 'zz', 'swap', 'i']\n"
     ]
    }
   ],
   "source": [
    "# print all (the usual suspects) available gates currently available within SDK\n",
    "gate_set = [attr for attr in dir(Gate) if attr[0] in string.ascii_uppercase]\n",
    "print('Gate set supported by SDK:\\n', gate_set)\n",
    "print('\\n') \n",
    "\n",
    "# the Rigetti device\n",
    "device = AwsDevice(\"arn:aws:braket:::device/qpu/rigetti/Aspen-9\")\n",
    "supported_gates = device.properties.action['braket.ir.jaqcd.program'].supportedOperations\n",
    "# print the supported gate set\n",
    "print('Gate set supported by the Rigetti device:\\n', supported_gates)\n",
    "print('\\n') \n",
    "\n",
    "# the IonQ device\n",
    "device = AwsDevice(\"arn:aws:braket:::device/qpu/ionq/ionQdevice\")\n",
    "supported_gates = device.properties.action['braket.ir.jaqcd.program'].supportedOperations\n",
    "# print the supported gate set\n",
    "print('Gate set supported by the IonQ device:\\n', supported_gates)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b076000f",
   "metadata": {},
   "source": [
    "### Access to State Vector, Amplitudes, Expectation Values\n",
    "As opposed to quantum hardware where only measurement shots can be obtained, with a classical simulator you can access the full state vector, amplitudes and expectation values of certain observables by assigning the corresponding result types. To do so, append the result types to the circuit before submitting it to run. This can be very useful for debugging."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "4dff1524",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T  : |0|1|  Result Types  |\n",
      "                           \n",
      "q0 : -H-C-Expectation(Z@Z)-\n",
      "        | |                \n",
      "q1 : ---X-Expectation(Z@Z)-\n",
      "\n",
      "T  : |0|1|  Result Types  |\n",
      "\n",
      "Additional result types: StateVector, Amplitude(11)\n"
     ]
    }
   ],
   "source": [
    "device = LocalSimulator()\n",
    "\n",
    "bell = Circuit().h(0).cnot(control=0, target=1)\n",
    "\n",
    "bell.state_vector()\n",
    "# add the Z \\otimes Z expectation value\n",
    "bell.expectation(Observable.Z() @ Observable.Z(), target=[0,1])\n",
    "# add the amplitude for |11>\n",
    "bell.amplitude(state=[\"11\"])\n",
    "# print circuit including requested result types\n",
    "print(bell)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "30540eff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Final EXACT state vector:\n",
      " [0.70710678+0.j 0.        +0.j 0.        +0.j 0.70710678+0.j]\n",
      "Expectation value <ZZ>: 0.9999999999999998\n",
      "Amplitude <11|Final state>: {'11': (0.7071067811865475+0j)}\n"
     ]
    }
   ],
   "source": [
    "# run the circuit and output the results\n",
    "task = device.run(bell, shots=0)\n",
    "result = task.result()\n",
    "\n",
    "# print results\n",
    "print(\"Final EXACT state vector:\\n\", result.values[0])\n",
    "print(\"Expectation value <ZZ>:\", result.values[1])\n",
    "print(\"Amplitude <11|Final state>:\", result.values[2])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0814689d",
   "metadata": {},
   "source": [
    "Clearly the expected results with perfect correlations between the three qubits making up the GHZ state are obtained.\n",
    "\n",
    "Note that you can only request state vector and amplitude when shots = 0 for a classical simulator. When shots = 0 for a simulator, you get the exact values of probability, expectation values, and variance, as derived from the full wave function. When shots > 0, you cannot access the full state vector, but you can get approximate expectation values as taken from measurement samples. Note that Amazon Braket also supports probability, sample, expectation, and variance as result types for QPU devices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c708c0b7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda_braket",
   "language": "python",
   "name": "conda_braket"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
